package generator.common

import org.apache.poi.hssf.usermodel.{HSSFSheet, HSSFWorkbook}
import org.apache.poi.ss.usermodel.CellStyle
import org.apache.poi.xssf.usermodel.{XSSFRow, XSSFSheet, XSSFWorkbook}

import java.io.{File, FileInputStream, FileOutputStream}

class ExcelWriter {
  var Workbook:XSSFWorkbook = null
  def createSheet(sheetIndex: Int, sheetName: String,fileName:String):XSSFSheet = {
    if (Workbook!=null) {
      var sheet:XSSFSheet = null

      try {
        sheet = Workbook.getSheet(sheetName)
      } catch {
        case e:IllegalArgumentException=> {
          println(e.getMessage)
        }
      }
      if (sheet==null) {
        sheet = Workbook.createSheet(sheetName)
      }
      val out = new FileOutputStream(fileName)
      Workbook.write(out)
      out.close
      return sheet
    } else {
      println("Workbook is null")
      null
    }
  }

  def open(fileName: String): FileInputStream = {
    val excelFile = new File(fileName)
    new FileInputStream(excelFile)
  }

  def openHSSFSheet(SheetIndex: Int = 0, fileName: String): HSSFSheet = {
    val Workbook = new HSSFWorkbook(open(fileName))
    Workbook.getSheetAt(SheetIndex)
  }

  def openXSSFWorkbook( fileName: String): Unit = {
    Workbook = new XSSFWorkbook(open(fileName))
  }

  def writeToHSSFSheet(fileName:String,Value:String,SheetIndex: Int = 0,RowIndex: Int = 0,CellIndex: Int = 0): Unit = {
    openHSSFSheet(SheetIndex, fileName).getRow(RowIndex).getCell(CellIndex).setCellValue(Value)
  }
  def writerToXSSFSheet(SheetName:String,fileName:String,Value:String,SheetIndex: Int = 0,RowIndex: Int = 0,CellIndex: Int = 0): Unit = {
//    val sheet = openXSSFSheet(SheetIndex, fileName)
    if (Workbook == null) {
      Workbook = new XSSFWorkbook(open(fileName))
    }
    var sheet = Workbook.getSheet(SheetName)
    if (sheet == null) {
      sheet = Workbook.createSheet(SheetName)
    }
    var row = sheet.getRow(RowIndex)
    if(row == null) {
      row = sheet.createRow(RowIndex)
    }
    var cell = row.getCell(CellIndex)
    if (cell == null) {
      cell = row.createCell(CellIndex)
    }
    cell.setCellValue(Value)
  }
  def write(fileName:String): Unit = {
    val out = new FileOutputStream(fileName)
    Workbook.write(out)
    out.close
  }
}

object ExcelWriter {
  def apply():ExcelWriter = {
    new ExcelWriter
  }
}
